<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
require_once(__DIR__ . "/../extend/common/app.php");

// 在线统计函数
function NumberHeartbeat($c = false, $t = 10)
{
    $online_log = __DIR__ . "/../runtime/count.dat"; //保存人数的文件,
    $timeout = $t; //x秒内没动作者,认为掉线
    $entries = file($online_log);
    $temp = array();
    for ($i = 0; $i < count($entries); $i++) {
        $entry = explode(",", trim($entries[$i]));
        if (($entry[0] != $_SERVER["REMOTE_ADDR"]) && ($entry[1] > time())) {
            //取出其他浏览者的信息,并去掉超时者,保存进$temp
            array_push($temp, $entry[0] . "," . $entry[1] . "\n");
        }
    }

    array_push($temp, $_SERVER["REMOTE_ADDR"] . "," . (time() + ($timeout)) . "\n"); //更新浏览者的时间
    $users_online = count($temp); //计算在线人数
    $entries = implode("", $temp);
    //写入文件
    $fp = fopen($online_log, "w");
    flock($fp, LOCK_EX); //flock() 不能在NFS以及其他的一些网络文件系统中正常工作
    fputs($fp, $entries);
    flock($fp, LOCK_UN);
    fclose($fp);

    if ($c) {
        return  $users_online;
    }
}
